package com.gui.pay.service.impl;

import com.github.wxpay.sdk.WXPayUtil;
import com.gui.entity.HttpClient;
import com.gui.pay.service.WxPayService;
import com.gui.registration.feign.RegistrationFeign;
import com.gui.registration.model.RegistrationRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 言叶
 * Date：2025/9/5
 */
@Service
public class WxPayServiceImpl implements WxPayService {
    @Value("${wx.pay.appId}")
    private String appId;
    @Value("${wx.pay.partner}")
    private String partner;
    @Value("${wx.pay.partnerKey}")
    private String partnerKey;
    @Value("${wx.pay.notifyUrl}")
    private String notifyUrl;
    @Autowired
    private RegistrationFeign registrationFeign;
    /*
     * 统一下单
     * @param body
     * @param outTradeNo
     * @param totalFee
     * @return
     */
    @Override
    public Map<String, String> unifiedOrder(String body, String outTradeNo, Long totalFee) {
        try {
        //调用第三方接口
        //1 明确接口地址   2  明确接口访问方式  3 明确接口参数  4 确定接口返回数据格式 Map    5 明确接口参数类型 xml
        String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
        HttpClient client = new HttpClient(url);
        //设置参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("mch_id", partner);
        map.put("nonce_str", WXPayUtil.generateNonceStr());
        map.put("notify_url", notifyUrl);
        map.put("spbill_create_ip", "127.0.0.1");
        map.put("trade_type", "APP");
        map.put("body", body);
        map.put("out_trade_no", outTradeNo);
        map.put("total_fee", totalFee+"");

        String xml = WXPayUtil.generateSignedXml(map, partnerKey);
        client.setXmlParam(xml);
        client.setHttps(true);
        client.post();
        String resultXml = client.getContent();
            return WXPayUtil.xmlToMap(resultXml);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateOrderStatus(RegistrationRecord record) {
        //调用挂号微服务，根据订单id更新微信订单号
        registrationFeign.updateRegistration(record);
    }
}
